let change_option = '';
let price_show = '';
let price_id = '';
let inventory_show = '';
let price1 = 0;
let price2 = 3288;
let inventory1 = 10;
let inventory2 = 12;
let commodity_options = {};

layui.use(['layer', 'form', 'carousel', 'jquery', 'element'], function () {
    var layer = layui.layer
        , form = layui.form
        , carousel = layui.carousel
        , $ = layui.$

  // 定义函数，根据选项，动态的展示价格和库存
    change_option = function (name, id, price, inventory, options) {
      if (name=='版本号'){
        price1 = price
        inventory1 = inventory
      }else{
        price2 = price
        inventory2 = inventory
      }
      price_show = price1 + price2
      inventory_show = inventory1 + inventory2
      price_id = id

      $(`#option${id}`).parent().children().css('border', '2px solid #DCDCDC')
      $(`#option${id}`).css('border', '2px solid red')
      commodity_options[name] = {
          'id': id,
          'price': price,
          'inventory': inventory,
          'options': options
      }
      $('.product-price').text('￥' + price_show)
      $('.inventory').text(inventory_show)
      // layer.alert(price1)
    }

  // 定义一个通过地址栏参数名称获取对应值的函数
  function GetQueryString(name) {
      let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      let r = window.location.search.substr(1).match(reg);
      if (r!=null){
          return decodeURI(r[2]);
      }else{
          return null;
      }
  }
  let id = GetQueryString('id');

  $.get('/commodity/info/get_options/',{"id":id},function (data) {
    op = data.data;
    // console.log(op);
    let content = ``;
    $.each(op,function (i,option) {
      content += `<li>
                        <span class="product-name">${option[0]}</span>
                        <ul class="options">`;
      commodity_options[option[0]] = option[1][0]
      $.each(option[1],function (j,dic) {
        let cls = ''
        price_id = dic.id
        price_show = dic.price
        inventory_show = dic.inventory
        if (j == 0){
          cls = 'class="pitch"'
        }
        content += `<li ${cls} id="option${dic.id}" onclick="change_option('${option[0]}',${dic.id},${dic.price},${dic.inventory},'${dic.options}')">`
        if (dic.image){
          content += `<img src="${dic.image}" title="${dic.options}">`;
        }else {
          content += dic.options;
        }
        content += `</li>`
      })
      content += `</ul>
                    </li>`
      $('#option-item').html(content);
      $('.inventory').text(inventory1+inventory2);
      $('.product-price').text('￥' + (price1+price2));
    })
  })

  $.get('/commodity/info/by_id/',{"id":id},function (data){
    data =data.data;
    $('#product-title').text(data.title);
    $('#product-subtitle').text(data.subtitle);
  })

  // 宝贝展示
  $.get('/commodity/info/by_src/',{"id":id, "belong":0},function (data){
    data = data.data;
    let content = ``;
    content += `<div class="mainImg" id="largePicDiv">
                    <img id="largePic" src="${data[0].src}" alt="宝贝">
                    <div class="zoom_pup" id="move"></div>
                    <div id="detailPic" class="big_pic">
                        <img src="${data[0].src}" alt="宝贝">
                    </div>
                </div>
                <div class="allImg" id="allImg">`
    $.each(data,function(i,dic){
      content += `<img src="${dic.src}" alt="宝贝">`
    })
    content += `</div>
            </div>`;
    $('#infoimg').html(content);

    // 实现放大镜效果
    $("#largePicDiv").mousemove(function (e) {
        $('.mainImg .zoom_pup').css("opacity", 0.3);
        $('.big_pic').css("display", "block");
        let ev = e || event;
        let mouseX = ev.pageX;
        let mouseY = ev.pageY;
        let picLeft = $("#largePic").offset().left;
        let picTop = $("#largePic").offset().top;
        let picWidth = $("#largePic").width();
        let picHeight = $("#largePic").height();
        let xLength = mouseX - picLeft;
        let yLength = mouseY - picTop;
        let qWidth = picWidth / 4;
        let lastQWidth = picWidth - picWidth / 4;
        let qHeight = picHeight / 4;
        let lastQHeight = picHeight - picHeight / 4;
        if (xLength < qWidth) {
            $("#move").css("left", "0px");
        } else {
            if (xLength > lastQWidth) {
                $("#move").css("left", (lastQWidth - qWidth) + "px");
            } else {
                $("#move").css("left", (xLength - qWidth) + "px");
            }
        }
        if (yLength < qHeight) {
            $("#move").css("top", "0px");
        } else {
            if (yLength > lastQHeight) {
                $("#move").css("top", (lastQHeight - qHeight) + "px");
            } else {
                $("#move").css("top", (yLength - qHeight) + "px");
            }
        }
        $("#detailPic > img").css("left", parseInt($("#move").css("left")) * (-800 / picWidth) + "px").css("top", parseInt($("#move").css("top")) * (-800 / picWidth) + "px").css("position", "absolute");
    }).mouseout(function () {
        $('.big_pic').css("display", "none");
        $('.mainImg .zoom_pup').css("opacity", 0);
    })

    // 实现选择展示图片，展示大图
    $(".allImg img").mouseover(function () {
        $(".allImg img").removeClass("current");
        $(this).addClass("current");
        var src = $(this).attr("src");
        $("#largePic").attr("src", src.replace("_x", "_w"));
        $("#detailPic img").attr("src", src.replace("_x", "_b"));
    });
  })

  // 宝贝详情
  $.get('/commodity/info/by_src/',{"id":id, "belong":1},function (data){
    data = data.data;
    let content = ``;
    $.each(data,function (i,dic) {
      content += `<img src="${dic.src}" alt="宝贝">`
    });
    $('#detail-img').html(content);
  });

  // 立即购物
  $('.shopping-btn').click(function () {
    let subject = `${$('#product-title').text()} | `
    for (let n in commodity_options){
      // console.log(n)
      subject += `${n}:${commodity_options[n].options} | `
    }
    // console.log(subject)
    // 登录状态限制
    if (!localStorage.getItem('Authorization')){
      layer.msg('未登录，亲，请登录！',{icon:5});
      setTimeout(function () {
        window.open('/static/login.html')
      },3000);
      return false;
    }
    $.ajax({
      type: 'POST',
      url: '/order/alipay/',
      headers: {
        'Authorization':localStorage.getItem('Authorization')
      },
      data: {
        'id': id,
        'option_id': price_id,
        'subject': subject,
      },
      success: function (data) {
        console.log(data)
        if (data.code==0){
          window.open(data.data);
        }else{
          layer.msg('异常终止',{icon:5})
        }
      }
    })
  })

})